<?php

namespace IDock\Insurance\HBIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\HBIC\HBICEnums;
use IDock\Printer\NonCar\NonCarProductPrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;
use IDock\Printer\SpecialClausesPrinter;
use IDock\Printer\VehiclePrinter;

class InsurancePriceQueryResponse extends AllHBICResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $this->setBody($body);
        }

        return $this;
    }

    public function printerInit(): Response
    {
        $premiumInquiryPrinter = new PremiumInquiryPrinter();
        //单独保存保费
        $premiumInquiryPrinter->argc['totalPremium'] = 0;
        $body = $this->getBody();
        $error = $body['HEAD']['ERROR_MESSAGE'] ?? '';
        if ($error && $body['HEAD']['ERROR_CODE'] != '0000') {
            $this->getRepeatData($premiumInquiryPrinter, $error, '');
            if ($premiumInquiryPrinter->repeatInsuredFlg) {
                $premiumInquiryPrinter->success = false;
                $premiumInquiryPrinter->repeatMessage = $error;
            } else {
                $this->setError($error);
            }
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        $premiumInquiryPrinter->success = true;
        $data = $this->getBody()['BODY'] ?? '';
        $basePart = $data['BASE_PART'] ?? [];
        $biData = $data['BI_INFO'] ?? [];
        $ciData = $data['CI_INFO'] ?? [];
        $point = $data['VEHICLERATINGLIST'] ?? [];
        $error = [];
        $biDesc = $biData['BI_MAIN']['REMARK'] ?? '';

        $this->getRepeatData($premiumInquiryPrinter, '', $biDesc);
        if ($premiumInquiryPrinter->repeatInsuredFlg) {
            $premiumInquiryPrinter->success = false;
            $premiumInquiryPrinter->repeatMessage = $biDesc;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }

        if (!empty($error)) {
            $this->setError(implode("\r\n", $error));
            $premiumInquiryPrinter->success = false;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        //交强险
        $premiumInquiryPrinter->inquiryNo = $basePart['QUOTATIONNO'] ?? '';//总询价单号
        $ciPremiumPrinter = new PremiumCIPrinter();
        $ciPremiumPrinter->ciPremium = $ciData['CI_MAIN']['STANDARDPREMIUM'] ?? 0;//交强险保费
        $ciPremiumPrinter->ciStartData = '';//交强险起保日期
        $ciPremiumPrinter->ciEndData = '';//交强险终保日期
        $ciPremiumPrinter->ciBasePremium = $ciData['CI_MAIN']['UWSTANDARDPREMIUM'] ?? '0';//交强险保费（不含增值税）
        $ciPremiumPrinter->ciDiscount = '1';//交强折扣率
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

        $carTaxPrinter = new PremiumTaxPrinter();
        $carTaxPrinter->carShipTax = $ciData['CARSHIPTAX']['SUMTAX'] ?? 0;
        $carTaxPrinter->thisYearTax = $ciData['CARSHIPTAX']['ANNUALTAXDUE'] ?? 0;//本年应缴税
        $carTaxPrinter->overdue = $ciData['CARSHIPTAX']['SUMOVERDUE'] ?? 0;
        $carTaxPrinter->payBackTax = $ciData['CARSHIPTAX']['SUMTAXDEFAULT'] ?? 0;
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;


        $biPremiumPrinter = new PremiumBIPrinter();
        $premiumInquiryPrinter->biInquiryNo = '';//商业险询价单号
        $biPremiumPrinter->biPremium = $biData['BI_MAIN']['SUMDISCOUNTPREMIUM'] ?? 0;//商业险保费
        $biPremiumPrinter->biStartData = '';//商业险起保日期
        $biPremiumPrinter->biEndData = '';//商业险终保日期
        $biPremiumPrinter->biBasePremium = '';//商业险基础保费 todo
        $biPremiumPrinter->biDiscount = round($biData['BI_MAIN']['DISCOUNT'] ?? 0, 4);
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;
        $premiumInquiryPrinter->argc['totalPremium'] = round($ciPremiumPrinter->ciPremium + $carTaxPrinter->carShipTax + $biPremiumPrinter->biPremium, 2);
        $coverageList = $biData['KIND_LIST']['KIND'] ?? [];
        $biBasePremium = 0;

        if (!isset($coverageList[0]) && !empty($coverageList)) {
            $tmp = $coverageList;
            unset($coverageList);
            $coverageList[] = $tmp;
        }
        if (!empty($coverageList)) foreach ($coverageList as $row) {
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($row['KINDCODE'], HBICEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            $coverage->amount = $row['SUMINSURED'] ?? 0;
            $coverage->premium = $row['PREMIUM'] ?? 0;
            $coverage->basePremium = $row['BASEPREMIUM'] ?? 0;
            $coverage->discount = $row['discountValue'] ?? 0;
            $biBasePremium += $row['BASEPREMIUM'] ?? 0;
            $premiumInquiryPrinter->coverageListAppend($coverage);
        }
        $biPremiumPrinter->biBasePremium = $biBasePremium;
        $modelData = $data['CICARMODELLIST']['CICARMODEL'] ?? [];
        $carModel = new VehiclePrinter();
        $carModel->vehicleName = $modelData['VEHICLE']['VEHICLENAME'] ?? '';
        $carModel->brandName = $modelData['BRAND'] ?? '';
        $carModel->familyName = $modelData['SERIES'] ?? '';
        $carModel->vehicleModelCode = $modelData['MODELCODE'] ?? '';
        $carModel->vehicleExhaust = $modelData['VEHICLE']['EXHAUSTSCALE'] ?? 0;
        $carModel->vehicleSeat = $modelData['VEHICLE']['SEATCOUNT'] ?? 0;
        $carModel->energyTypeCode = '';
        $carModel->wholeWeight = $modelData['VEHICLE']['COMPLETEKERBMASS'] ?? '';
        $premiumInquiryPrinter->vehicleModelAppend($carModel);
        //特约
        $engageList = [];
        $clauseList = $biData['SPECIALCLAUSE_LIST'] ?? [];
        $jqClauseList = $ciData['SPECIALCLAUSE_LIST'] ?? [];

        if (!isset($jqClauseList['SPECIALCLAUSE'][0]) && isset($jqClauseList['SPECIALCLAUSE'])) {
            $tmp = $jqClauseList['SPECIALCLAUSE'];
            unset($jqClauseList['SPECIALCLAUSE']);
            $jqClauseList['SPECIALCLAUSE'][] = $tmp;
        }
        if (!empty($jqClauseList['SPECIALCLAUSE'])) foreach ($jqClauseList['SPECIALCLAUSE'] as $val) {

            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['CLAUSECNAME'] ?? '';
            $engage->clauseCode = $val['CLAUSECODE'] ?? '';
            $engage->clauseContent = empty($val['CONTEXT']) ? '' : $val['CONTEXT'];
            $engage->autoFlag = in_array($val['MODIFYIND'], ['4', '8']) ? 1 : 0;
            $engage->riskType = 'TCI';//交强险特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        if (!isset($clauseList['SPECIALCLAUSE'][0]) && isset($clauseList['SPECIALCLAUSE'])) {
            $tmp = $clauseList['SPECIALCLAUSE'];
            unset($clauseList['SPECIALCLAUSE']);
            $clauseList['SPECIALCLAUSE'][] = $tmp;
        }
        if (!empty($clauseList['SPECIALCLAUSE'])) foreach ($clauseList['SPECIALCLAUSE'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['CLAUSECNAME'];
            $engage->clauseCode = $val['CLAUSECODE'];
            $engage->clauseContent = empty($val['CONTEXT']) ? '' : $val['CONTEXT'];
            $engage->autoFlag = in_array($val['MODIFYIND'], ['4', '8']) ? 1 : 0;
            $engage->riskType = 'VCI';//商业险特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }

        //交商系数
        $riskList = $data['RISKITEMLIST']['RISKITEM'] ?? [];
        $factorPrinter = new PremiumFactorPrinter();
        foreach ($riskList as $val) {
            if ($val['FACTORCODE'] == 'F03') {
                $premiumInquiryPrinter->ncdFactor = round($val['ADJUSTVALUE'] / 100, 2) ?? '';
            } elseif ($val['FACTORCODE'] == 'F04') {
                $factorPrinter->VCIFactorAppend('交通违法系数', 'nResvNum8', $val['ADJUSTVALUE'] / 100 ?? '');
            }
        }
        $pList = $point['VEHICLERATING'] ?? [];
        $pList = $this->formatArray($pList);
        if (!empty($pList)) foreach ($pList as $value) {
            $factorPrinter->ComFactorAppend(HBICEnums::$pointType[$value['SCORINGTYPE'] ?? ''] ?? '', 'SCORINGTYPE1', $value['SCORING'] ?? '');
        }
        //赔付率信息
        $rateList = $data['PRECOMPENSATIONRATELIST']['PRECOMPENSATIONRATE'] ?? [];

        if (isset($rateList[0])) {
            foreach ($rateList as $val) {
                $factorPrinter->TCIFactorAppend('交强险赔付率(%)', 'ciJqecompensationRate', $val['BILLCTPELR'] ?? '');
                $factorPrinter->TCIFactorAppend('商业险赔付率(%)', 'biNecompensationRate', $val['BILLCOMELR'] ?? '');
                $factorPrinter->ComFactorAppend('整单预期赔付率', 'billELR', $val['BILLELR'] ?? '');
            }
        } else {
            $factorPrinter->TCIFactorAppend('交强险赔付率(%)', 'ciJqecompensationRate', $rateList['BILLCTPELR'] ?? '');
            $factorPrinter->TCIFactorAppend('商业险赔付率(%)', 'biNecompensationRate', $rateList['BILLCOMELR'] ?? '');
            $factorPrinter->ComFactorAppend('整单预期赔付率', 'billELR', $rateList['BILLELR'] ?? '');
        }

        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;
        $this->printer = $premiumInquiryPrinter;
        return $this;
    }

    public function NcSpecialClause($clauseList, PremiumInquiryPrinter $premiumInquiryPrinter)
    {
        $list = [];
        if (!empty($clauseList)) foreach ($clauseList as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['name'];
            $engage->clauseCode = $val['code'];
            $engage->clauseContent = $val['content'] ?? '';
            $engage->autoFlag = 0;
            $engage->riskType = 'NC';//商业险特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
            $list[] = $engage;
        }
        $product = new NonCarProductPrinter();
        $product->argc['specialClause'] = $list;
        $premiumInquiryPrinter->nonCarProductListPrinter->productListAppend($product);
        return $premiumInquiryPrinter;
    }

    /**
     * 重复投保
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @param $ciMeg
     * @param $biMeg
     */
    public function getRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $ciMeg, $biMeg)
    {

        if ($ciMeg and preg_match('/终保日期 ([\d\s:-]+)/', $ciMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;
                $premiumInquiryPrinter->repeatMessage = $ciMeg;
            }
        }


        if ($biMeg and preg_match('/终保日期：([\d\s:-]+)/', $biMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;
                $premiumInquiryPrinter->repeatMessage = $biMeg;
            }
        }
    }
}
